package com.briup.cms.web.interceptor;

import com.briup.cms.bean.User;
import com.briup.cms.dao.UserDao;
import com.briup.cms.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

//Vip拦截器
@Slf4j
@Component
public class VipCheckInterceptor implements HandlerInterceptor {
    @Autowired
    private UserDao userDao;
    // 拦截器前置处理方法
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        //1.获取当前登录用户
        String token = request.getHeader("Authorization");
        //log.info("in preHandler token: " + token);
        Long userId = JwtUtil.getUserId(token);
        User user = userDao.selectById(userId);
        log.info("当前用户: {}, 是否为vip: {}", userId, user.getIsVip());
        //2.如果当前用户是vip，过期判断及修改
        if(user.getIsVip() == 1) {
            int n = LocalDateTime.now().compareTo(user.getExpiresTime());
            //log.info("是否超时: {}", n);
            if(n >= 0) {
                //log.info("vip已过期");
                User u = new User();
                u.setId(userId);
                u.setIsVip(0);
                userDao.updateById(u);
            }
        }
        // 3.放行
        return true;
    }
}